<template>
  <div class="profile">
    <div class="container">
      <h1>个人中心</h1>
      <div v-if="userStore.isAuthenticated" class="profile-content">
        <!-- 资料卡片 -->
        <div class="profile-card">
          <div class="avatar">
            <img :src="avatarSrc" alt="用户头像" />
          </div>
          <div class="profile-form">
            <div class="form-row">
              <label>用户名</label>
              <input type="text" v-model="form.username" disabled />
            </div>
            <div class="form-row">
              <label>姓名</label>
              <input type="text" v-model="form.realName" placeholder="您的真实姓名" :class="{ error: errors.realName }" :disabled="!isEditing" />
              <span v-if="errors.realName" class="error-message">{{ errors.realName }}</span>
            </div>
            <div class="form-row">
              <label>邮箱</label>
              <input type="email" v-model="form.email" placeholder="name@example.com" :class="{ error: errors.email }" :disabled="!isEditing" />
              <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
            </div>
            <div class="form-row">
              <label>手机号</label>
              <input type="tel" v-model="form.phone" placeholder="139********" :class="{ error: errors.phone }" :disabled="!isEditing" />
              <span v-if="errors.phone" class="error-message">{{ errors.phone }}</span>
            </div>
            <div class="form-row">
              <!-- 移除头像地址输入，仅保留上传方式 -->
            </div>
            <div class="form-row" v-if="isEditing">
              <label>上传头像</label>
              <input type="file" accept="image/*" @change="onAvatarSelected" />
              <div class="hint" style="font-size:12px;color:#888;">支持 .png/.jpg/.jpeg/.webp</div>
              <button class="btn btn--small" @click="uploadAvatar" :disabled="saving">上传</button>
            </div>
            <div class="actions">
              <button v-if="!isEditing" class="btn btn--primary" @click="startEdit">编辑资料</button>
              <button v-else class="btn btn--primary" @click="saveProfile" :disabled="saving">保存资料</button>
              <button class="btn btn--secondary" @click="userStore.logout">退出登录</button>
            </div>
          </div>
        </div>

        <!-- 收藏列表 -->
        <div class="collection-section">
          <h2>我的收藏</h2>
          <div v-if="favorites.length === 0" class="empty">暂无收藏，前往演出详情页添加收藏。</div>
          <div v-else class="grid">
            <div v-for="item in favorites" :key="`fav-${item.id}`" class="card">
              <img :src="item.image" :alt="item.title" />
              <div class="card-info">
                <h3>{{ item.title }}</h3>
                <p>{{ item.venue }} | {{ formatDate(item.date) }}</p>
              </div>
              <div class="card-actions">
                <RouterLink :to="`/event/${item.id}`" class="btn btn--small">查看</RouterLink>
                <button class="btn btn--small btn--danger" @click="removeFavorite(item.id)">取消收藏</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 最近浏览 -->
        <div class="recent-section">
          <div class="recent-header">
            <h2>最近浏览</h2>
            <button class="btn btn--secondary btn--small" @click="clearRecent" :disabled="recent.length === 0">清空</button>
          </div>
          <div v-if="recent.length === 0" class="empty">暂无浏览历史。</div>
          <div v-else class="grid">
            <div v-for="item in recent" :key="`rec-${item.id}`" class="card">
              <img :src="item.image" :alt="item.title" />
              <div class="card-info">
                <h3>{{ item.title }}</h3>
                <p>{{ item.venue }} | {{ formatDate(item.date) }}</p>
              </div>
              <div class="card-actions">
                <RouterLink :to="`/event/${item.id}`" class="btn btn--small">再看看</RouterLink>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="auth-empty">
        <div class="auth-card">
          <div class="auth-illustration">👋</div>
          <h2>尚未登录</h2>
          <p class="auth-tip">登录后可管理个人资料、查看订单与收藏。</p>
          <div class="auth-actions">
            <RouterLink to="/login" class="btn btn--primary">立即登录</RouterLink>
            <RouterLink to="/register" class="btn btn--secondary">快速注册</RouterLink>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { useActivityStore } from '@/stores/activity'
import { useToastStore } from '@/stores/toast'
import { BASE_URL } from '@/api/client'

const userStore = useUserStore()
const activityStore = useActivityStore()
const toast = useToastStore()

const form = ref({
  username: '',
  realName: '',
  email: '',
  phone: ''
})

// 编辑模式：默认只读，需要点击“编辑资料”
const isEditing = ref(false)

// 初始化表单数据
const initializeForm = () => {
  if (userStore.user) {
    form.value = {
      username: userStore.user.username || '',
      realName: userStore.user.realName || '',
      email: userStore.user.email || '',
      phone: userStore.user.phone || ''
    }
  }
}

// 监听用户信息变化，自动更新表单
watch(() => userStore.user, (newUser) => {
  if (newUser) {
    initializeForm()
  }
}, { immediate: true, deep: true })

// 组件挂载时初始化表单
onMounted(async () => {
  // 初始化缓存态，并尝试从后端拉取最新资料
  userStore.initUser()
  try { await userStore.fetchProfile() } catch (_) {}
  initializeForm()
})

const avatarSrc = computed(() => {
  const a = userStore.user?.avatar || '/src/assets/images/default-avatar.svg'
  if (a.startsWith('/uploads/')) return `${BASE_URL}${a}`
  return a
})
const saving = ref(false)

const errors = ref({
  realName: '',
  email: '',
  phone: ''
})

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const phoneRegex = /^1[3-9]\d{9}$/

const validateProfile = () => {
  errors.value.realName = ''
  errors.value.email = ''
  errors.value.phone = ''
  let ok = true
  if (!form.value.realName || form.value.realName.trim().length < 2) {
    errors.value.realName = '姓名至少2个字符'
    ok = false
  }
  if (!form.value.email || !emailRegex.test(form.value.email)) {
    errors.value.email = '请输入有效的邮箱地址'
    ok = false
  }
  if (!form.value.phone || !phoneRegex.test(form.value.phone)) {
    errors.value.phone = '请输入有效的手机号码'
    ok = false
  }
  return ok
}

const saveProfile = async () => {
  if (!validateProfile()) {
    toast.error('请修正表单中的错误后再保存')
    return
  }
  saving.value = true
  const resp = await userStore.updateProfile({ ...form.value })
  saving.value = false
  if (resp?.success) {
    toast.success('资料已保存')
    isEditing.value = false
  } else {
    toast.error(`保存失败：${resp?.error || '未知错误'}`)
  }
}

const startEdit = () => {
  // 进入编辑模式并清理校验错误
  isEditing.value = true
  errors.value = { realName: '', email: '', phone: '' }
}

// 头像上传
const selectedFile = ref(null)
const onAvatarSelected = (e) => {
  const f = e.target.files?.[0]
  selectedFile.value = f || null
}
const uploadAvatar = async () => {
  if (!selectedFile.value) {
    toast.warning('请选择图片文件')
    return
  }
  saving.value = true
  const resp = await userStore.uploadAvatar(selectedFile.value)
  saving.value = false
  if (resp?.success) {
    toast.success('头像上传成功')
  } else {
    toast.error(`头像上传失败：${resp?.error || '未知错误'}`)
  }
}

const favorites = computed(() => activityStore.favorites)
const recent = computed(() => activityStore.recent)
const removeFavorite = (id) => activityStore.removeFavorite(id)
const clearRecent = () => activityStore.clearRecent()

const formatDate = (dateStr) => {
  const d = new Date(dateStr)
  return d.toLocaleString('zh-CN', { year: 'numeric', month: 'short', day: 'numeric' })
}
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as *;

.profile {
  min-height: 100vh;
  padding: $spacing-xl 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.profile::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 300px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  z-index: 0;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: $spacing-xl;
  position: relative;
  z-index: 1;
}

.profile-card {
  display: grid;
  grid-template-columns: 180px 1fr;
  gap: $spacing-xl;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  padding: $spacing-xxl;
  border: 1px solid rgba(255,255,255,0.2);
  backdrop-filter: blur(10px);
}

.avatar {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: $spacing-md;
}

.avatar img {
  width: 160px;
  height: 160px;
  object-fit: cover;
  border-radius: 50%;
  border: 4px solid #fff;
  box-shadow: 0 8px 32px rgba(0,0,0,0.15);
  transition: transform 0.3s ease;
}

.avatar img:hover {
  transform: scale(1.05);
}

.profile-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: $spacing-lg $spacing-xl;
}

.form-row {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-row label {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.form-row input {
  padding: 14px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.form-row input:focus {
  outline: none;
  border-color: #667eea;
  background: #fff;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-row input.error {
  border-color: #ef4444;
  background: #fef2f2;
}

.error-message {
  color: #e74c3c;
  font-size: 13px;
}

.actions {
  grid-column: 1 / span 2;
  display: flex;
  gap: $spacing-md;
  margin-top: $spacing-xl;
  justify-content: flex-end;
}

.actions .btn {
  padding: 12px 24px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s ease;
  border: none;
  cursor: pointer;
}

.actions .btn--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.actions .btn--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
}

.actions .btn--secondary {
  background: #f3f4f6;
  color: #374151;
  border: 2px solid #e5e7eb;
}

.actions .btn--secondary:hover {
  background: #e5e7eb;
  transform: translateY(-1px);
}

.collection-section, .recent-section {
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.08);
  padding: $spacing-xxl;
  border: 1px solid rgba(255,255,255,0.2);
}

.recent-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-lg;
}

.recent-header h2 {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.grid {
  margin-top: $spacing-lg;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: $spacing-xl;
}

.card {
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 25px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
  border: 1px solid #f3f4f6;
}

.card:hover {
  transform: translateY(-8px);
  box-shadow: 0 20px 40px rgba(0,0,0,0.15);
}

.card img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.card:hover img {
  transform: scale(1.05);
}

.card-info {
  padding: $spacing-md $spacing-lg;
  flex: 1;
}

.card-info h3 {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1f2937;
  line-height: 1.4;
}

.card-info p {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
}

.card-actions {
  display: flex;
  gap: $spacing-sm;
  padding: $spacing-md $spacing-lg $spacing-lg;
  border-top: 1px solid #f3f4f6;
}

.card-actions .btn {
  flex: 1;
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
  text-align: center;
  transition: all 0.2s ease;
  border: none;
  cursor: pointer;
}

.card-actions .btn-primary {
  background: #667eea;
  color: white;
}

.card-actions .btn-primary:hover {
  background: #5a67d8;
}

.card-actions .btn-secondary {
  background: #f9fafb;
  color: #374151;
  border: 1px solid #e5e7eb;
}

.card-actions .btn-secondary:hover {
  background: #f3f4f6;
}

.empty {
  color: #9ca3af;
  text-align: center;
  padding: $spacing-xxl 0;
  font-size: 16px;
  background: #f9fafb;
  border-radius: 12px;
  margin: $spacing-lg 0;
}

/* 未登录态美化 */
.auth-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: $spacing-xxl 0;
}
.auth-card {
  background: #ffffff;
  border: 1px solid #e5e7eb; /* 方框统一颜色，与页面风格一致 */
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.08);
  padding: $spacing-xl $spacing-xxl;
  text-align: center;
  max-width: 520px;
}
.auth-illustration {
  font-size: 48px;
  line-height: 1;
  margin-bottom: $spacing-sm;
}
.auth-tip { color: #64748b; margin: $spacing-xs 0 $spacing-md; }
.auth-actions { display: flex; gap: $spacing-sm; justify-content: center; }
.auth-actions .btn--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  border: none;
  cursor: pointer;
}
.auth-actions .btn--primary:hover {
  background: #5a67d8; /* 悬浮更明显 */
}
.auth-actions .btn--secondary { background: #eef2ff; color: #4f46e5; }
.auth-actions .btn--secondary:hover { background: #e0e7ff; }

/* 版式优化：容器宽度与标题样式 */
.profile .container {
  max-width: 1080px;
  margin: 0 auto;
}

.profile h1 {
  color: #ffffff;
  font-weight: 700;
  letter-spacing: 0.5px;
  margin-bottom: $spacing-lg;
  text-shadow: 0 2px 10px rgba(0,0,0,0.14);
}

@media (max-width: $breakpoint-md) {
  .profile {
    padding: $spacing-lg 0;
  }
  
  .profile-card {
    grid-template-columns: 1fr;
    text-align: center;
    padding: $spacing-xl;
  }
  
  .avatar { 
    display: grid; 
    place-items: center; 
  }
  
  .profile-form { 
    grid-template-columns: 1fr;
    gap: $spacing-md;
  }
  
  .actions { 
    justify-content: center;
    flex-direction: column;
  }
  
  .grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: $spacing-md;
  }
  
  .collection-section, .recent-section {
    padding: $spacing-lg;
  }
}
</style>